#include "buffer.h"

#include <sys/uio.h>
#include <unistd.h>

using namespace tiny_muduo;
char extrabuf[65536] = {0};

int Buffer::ReadFd_ET(int fd, bool& recv_null) {
	int read_total = 0;
	int extra_size = sizeof(extrabuf);
	while(1){
		int readn = read(fd, extrabuf, extra_size);
		if (readn < 0) {
			if(errno == EAGAIN || errno == EWOULDBLOCK){
				break;
			}
				
			printf("Buffer::ReadFd readn < 0 SYS_ERR\n");
			return -1;
		}
		else if(readn == 0){
			recv_null = 1;
			break;
		}
		else
			Append(extrabuf, readn);
		
		read_total += readn;
	}

	return read_total;
}

int Buffer::ReadFd_LT(int fd) {
	char extrabuf[65536] = {0};
	struct iovec iv[2];
	const int writable = writablebytes();
	iv[0].iov_base = beginwrite();
	iv[0].iov_len = writable;
	iv[1].iov_base = extrabuf;
	iv[1].iov_len = sizeof(extrabuf);
	
	const int iovcnt = (writable < static_cast<int>(sizeof(extrabuf)) ? 2 : 1);
	int readn = readv(fd, iv, iovcnt);

	if (readn < 0) {
		printf("Buffer::ReadFd readn < 0 SYS_ERR\n");
	}else if (readn <= writable) {
		write_index_ += readn;
	} else {
		write_index_ = buffer_.size();
		Append(extrabuf, readn - writable);
	}

	return readn;
}


void Buffer::Debug(){
	printf("Buffer::Debug read_index_:%d write_index_:%d\n", read_index_, write_index_);
	printf("---------- buffer content ------------\n");
	for(auto c : buffer_){
		printf("%c", c);
	}
	printf("---------- end ------------\n");
}